package springsecurityrabclogin.handler;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import springsecurityrabclogin.result.R;

import java.io.IOException;
/**
 * 登录失败 ，会执行该方法
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("/application/json");
        response.setCharacterEncoding("utf-8");
        //采用构建器模式，链式编程创建一个R对象
        R result = R.builder().code(500).msg("登录失败: " + exception.getMessage()).build();

        //利用hutool工具包，把R对象转成字符串
        String json = JSONUtil.toJsonStr(result);

        //把json写出去，写出到浏览器客户端
        response.getWriter().write(json);
    }
}
